package org.hhh.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xml.internal.security.Init;
import org.hhh.basic.constant.BaseConstants;
import org.hhh.basic.exception.BusinessException;
import org.hhh.basic.util.AjaxResult;
import org.hhh.basic.util.HttpClientUtils;
import org.hhh.basic.util.MD5Utils;
import org.hhh.basic.util.StrUtils;
import org.hhh.user.domain.Logininfo;
import org.hhh.user.domain.User;
import org.hhh.user.domain.WxUser;
import org.hhh.user.dto.LoginDto;
import org.hhh.user.dto.UserDto;
import org.hhh.user.mapper.LogininfoMapper;
import org.hhh.user.mapper.UserMapper;
import org.hhh.user.mapper.WxUserMapper;
import org.hhh.user.service.ILoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;
    @Override
    public Map<String, Object> accountLogin(LoginDto dto) {
        //1.校验
        if (StringUtils.isEmpty(dto.getUsername())
                ||StringUtils.isEmpty(dto.getPassword())
                || dto.getType()==null){
            throw new BusinessException("请输入相关信息后再登录！");
        }
        //2.根据用户名查询数据库
        Logininfo logininfo=logininfoMapper.loadByUserName(dto);
        //2.1查询账号存在不
        if (logininfo == null) {
            throw new BusinessException("用户名不存在！");
        }
        //2.2查询密码是否正确
        //加盐
        String salt = logininfo.getSalt();
        //对数据盐值加密之后的密码
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        if(!logininfo.getPassword().equals(md5Pwd)){
            throw new BusinessException("用户名不存在！");
        }
        //3.登录成功
        String token = UUID.randomUUID().toString();//生成随机串token
        //3.1保存redis
        redisTemplate.opsForValue().set(token,
                logininfo,//序列化对象
                30,
                TimeUnit.MINUTES);
        //3.2返回登录的信息
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        return map;

    }

    @Override
    public AjaxResult wechat(String code) {
        //参数校验
        if (StringUtils.isEmpty(code)){
            throw new BusinessException("参数不能为空！！！");
        }
        //根据code从微信获取access_token的链接
        String tokenUrl= BaseConstants.GET_TOKEN_URL
                .replace("APPID", BaseConstants.APPID)
                .replace("SECRET", BaseConstants.SECRET)
                .replace("CODE", code);
        //使用http发送请求到微信获取coken+openId
        String tokenStr = HttpClientUtils.httpGet(tokenUrl);
        //把json字符串转成json对象
        JSONObject jsonObject = JSONObject.parseObject(tokenStr);
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        //根据openId查询t_wxuser表
        WxUser wxUser = wxUserMapper.loadByOpenId(openId);
        //判断是否微信扫码登录过
        if (wxUser != null && wxUser.getUser_id()!=null) {
            //账号存在，直接登录
            //根据userid查询logininfo
            Logininfo logininfo=logininfoMapper.loadByUserId(wxUser.getUser_id());
            //3.登录成功
            String token = UUID.randomUUID().toString();//生成随机串token
            //3.1保存redis
            redisTemplate.opsForValue().set(token,
                    logininfo,//序列化对象
                    30,
                    TimeUnit.MINUTES);
            //3.2返回登录的信息
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("logininfo", logininfo);
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            return AjaxResult.me().setResultObj(map);
        }else {//第一次扫描，需要跳转到绑定页面，进行微信绑定注册
            String binderParams = "?accessToken="+accessToken+"&openId="+openId;
            return AjaxResult.me().setSuccess(false).setResultObj(binderParams);
        }
    }

    @Override
    public Map<String, Object> binderWechat(Map<String, String> params) {
        //获取参数
        String phone = params.get("phone");
        String verifyCode = params.get("verifyCode");
        String accessToken = params.get("accessToken");
        String openId = params.get("openId");
        //参数校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(openId)){
            throw new BusinessException("参数不明！！！");
        }
        //验证码校验
        //验证是否过期
        Object codeTmp = redisTemplate.opsForValue().get(BaseConstants.BUSINESS_BINDER_PREFIX + phone);
        if (codeTmp == null) {
            throw new BusinessException("验证码已经过期了！！！");
        }
        //2.2验证码是否填写正确
        String code=((String) codeTmp).split(":")[0];
        if (!verifyCode.equalsIgnoreCase(code)){//不区分大小写
            throw new BusinessException("请填写正确的验证码！！！");
        }

        //查询手机号是否注册过
        User user = userMapper.loadByPhone(phone);
        Logininfo logininfo=null;
        if (user!=null){
            //查询已经存在的用户做微信绑定
            logininfo=logininfoMapper.loadById(user.getLogininfo_id());
        }else {
            //没有被注册，要生成新的
            user= initUser(phone);
            logininfo=User2Logininfo(user);
            //保存logininfo
            logininfoMapper.save(logininfo);
            //保存user
            user.setLogininfo_id(logininfo.getId());
            userMapper.save(user);
        }

        //调用微信，查询用户微信基本信息
        //拼接获取微信基本信息的URL
        String WxUserURL = BaseConstants.GET_WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        //获取微信用户基本信息，把json对象转为WxUser对象
        String wxUserStr = HttpClientUtils.httpGet(WxUserURL);
        WxUser wxUser = JSONObject.parseObject(wxUserStr, WxUser.class);
        wxUser.setUser_id(user.getId());//绑定用户
        wxUserMapper.save(wxUser);//保存
        //登录成功
        //3.登录成功
        String token = UUID.randomUUID().toString();//生成随机串token
        //3.1保存redis
        redisTemplate.opsForValue().set(token,
                logininfo,//序列化对象
                30,
                TimeUnit.MINUTES);
        //3.2返回登录的信息
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        return map;
    }


    private User initUser(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //使用盐值加密
        String md5 = MD5Utils.encrypByMd5("1"+ salt);
        //发送短信告诉用户初始密码并自己修改
        user.setSalt(salt);
        user.setPassword(md5);
        return user;
    }

    private Logininfo User2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //同名拷贝
        BeanUtils.copyProperties(user,logininfo );
        logininfo.setType(1);
        return logininfo;
    }
}
